package com.gl.basis.zuul.filter;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gl.basis.auth.constants.AuthorityConstants;
import com.gl.basis.common.constant.ResultCode;
import com.gl.basis.common.pojo.CommBean;
import com.gl.basis.common.pojo.CommonResult;
import com.gl.basis.util.RedisUtil;
import com.gl.basis.zuul.entity.SysAppMapping;
import com.gl.basis.zuul.enums.RouteType;
import com.gl.basis.zuul.service.ISysAppMappingService;
import com.gl.basis.zuul.util.RequestUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * 	幂等业务
 * @author admin
 *
 */

@Component
public class IdempotencyFilter extends ZuulFilter {

	@Autowired
	private RedisUtil redisUtil;
	@Resource
	public ISysAppMappingService sysAppMappingService;
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 200;
	}
	
	@Override
	public boolean shouldFilter() {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
        String path = request.getServletPath();
        //包含api就不转发
        if (!currentContext.sendZuulResponse() ||( StringUtils.isNotBlank(path)&& path.contains(RouteType.API.getCode()))) {
			return false;
		}
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		String requestParams = RequestUtils.getRequestParams(currentContext, request);
		CommBean reqParams = JSONObject.parseObject(requestParams, CommBean.class);
		
		SysAppMapping mappingUrl = sysAppMappingService.findAppMappingUrl(reqParams.getMethod());
		String reqsign = reqParams.getSign();
		if (null != mappingUrl && StringUtils.isNotBlank(mappingUrl.getIdempotents())
				&&AuthorityConstants.DEMPOTENCY_CODE.equalsIgnoreCase(mappingUrl.getIdempotents()) 
				&&StringUtils.isNotBlank(reqsign) && redisUtil.exists(AuthorityConstants.GATEWAY_IDEMPOTENCY+reqsign)) {
			currentContext.setSendZuulResponse(false);
			HttpServletResponse response = currentContext.getResponse();
			response.setContentType(AuthorityConstants.APPLICATION_JSON);
			currentContext.setResponseBody(JSON.toJSONString(CommonResult.failed(ResultCode.IDEMPOTENCY_ERROR)));
		}
		
		
		return null;
	}


}
